/* eslint-disable strict */
/* eslint-disable no-unused-vars */
const ws = require('nodejs-websocket');
// 记录用户
var count = 1
const server = ws.createServer(socket => {

  console.log('socket.io连接成功', socket);
  count++
  console.log(count+'进入直播间');

  // 进入直播间返回系统消息 ，第一次链接返回的消息
  talk(JSON.stringify({
    name: '系统消息',
    comment: `欢迎用户${socket.headers.name ?socket.headers.name :count}来到直播间`,
  }));
  // 返回给前端 接到前端发来的消息
  socket.on('text', data => {
    console.log('received: ' + data);
    const userData = JSON.parse(data);

    talk(JSON.stringify({
      name: userData.name,
      comment: userData.comment,
      img: userData.img,
    }));
    // socket.sendText();
  });
  socket.on('close', (code, reason) => {
    console.log(count+'用户离开了');
    count--
  });
  socket.on('error', () => {
    console.log('connection error!');
  });
});
// 把信息发送给所有服务器
function talk(msg) {
  server.connections.forEach(connect => {
    connect.send(msg);
  });
}
server.listen('8000', () => {
  console.log('websocket server start at ws://10.31.71.55:9000');
});
